package com.soap.ResumeAim.service;

import com.hankcs.hanlp.seg.common.Term;
import com.soap.ResumeAim.utils.ImgUtils;
import com.soap.ResumeAim.controller.req.IdentifyReq;
import net.sourceforge.tess4j.Tesseract;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: Soap
 * @date: 2021/11/1
 * @desc: 图片进行预处理
 */
@Service
public class ResumeService {

    @Value("${paddle.host}")
    private String host;
    @Value("${paddle.port}")
    private String port;
    @Value("${paddle.url}")
    private String url;

    /**
     * 调用paddleOCR提供的OCR功能进行简历的识别
     * @param req
     * @return
     * @throws Exception
     */
    public List<String> indentifyResume(IdentifyReq req) throws Exception {

        //参数校验，如果图片格式不符合要求则预处理
        if (req.getImgPath().endsWith("pdf")){
            //TODO 譬如pdf有多张，这里暂时只处理第一张
            req.setImgPath(ImgUtils.pdf2jpg(req.getImgPath()).get(0));
        }

        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间：15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建post请求方法实例对象
        PostMethod postMethod = new PostMethod(this.url);
        //设置请求参数
        postMethod.setRequestEntity(new StringRequestEntity(new JSONObject(req).toString() , "application/json" , "UTF-8"));
        // 设置post请求超时时间
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        postMethod.addRequestHeader("Content-Type", "application/json");
        httpClient.executeMethod(postMethod);
        //sb Python用单引号
        String resume = postMethod.getResponseBodyAsString().replaceAll("'" , "");
        //去除开头和结尾的中括号
        if (resume.startsWith("[")){
            resume = resume.substring(1 , resume.length());
        }
        if (resume.endsWith("]")){
            resume = resume.substring(0 , resume.length() - 1);
        }
        //利用插眼换行
        List<String> breakList = Arrays.asList(resume.split(", breakFlag9527, "));
        //python为了统一插眼格式，这边解析的时候会多出一个空元素，进行去除
        ArrayList<String> resList = new ArrayList<>(breakList);
        resList.remove(resList.size() - 1);

        //TODO 这里理应对解析后的元素个数与python传递来的进行一个比较，后续再说
        return resList;
    }

    /**
     * 对简历进行分词以提取关键字
     */
    public List<Term> analyzeResume(String resume){

        return null;
    }
}
